<script lang="ts">
    export default {
        name: 'Pay',
    };
</script>

<script setup lang="ts">
    import { ref, computed, onMounted } from 'vue';
    import { showConfirmDialog, showToast, showLoadingToast, closeToast } from 'vant';
    import { useRouter, useRoute } from 'vue-router'
    import { useShopNav } from '@/store/modules/app';
    import { useI18n } from 'vue-i18n';
    import API_ORDER from '@/apis/order'
    import QRCode from 'qrcode';
    const { t } = useI18n();
    const appStore = useShopNav();
    const router = useRouter();
    const route = useRoute();
    let order_sn = ref('')

    // 订单信息
    let orderInfo = ref({
        id: 'ORD20230915' + Math.floor(Math.random() * 10000),
        amount: 299.00,
        description: '高级会员套餐 (12个月)',
        createdAt: new Date(),
    });

    // 支付方式
    const paymentMethods = ref([
        {
            id: 'paypal',
            name: 'PayPal',
            icon: 'paypal',
            color: '#003087',
            description: t('home.use') + 'PayPal' + t('home.pay'),
            selected: true
        },
        {
            id: 'usdt',
            name: 'USDT',
            icon: 'usdt',
            color: '#26a17b',
            description: t('home.use') + 'USDT' + t('home.pay'),
            selected: false
        },
        {
            id: 'yue',
            name: t('home.Balance'),
            icon: 'yue',
            color: '#26a17b',
            description: t('home.use') + t('home.Balance') + t('home.pay'),
            selected: false
        }
    ]);

    // 当前选择的支付方式
    const selectedMethod = ref('paypal');

    // USDT 支付信息
    let usdtInfo = ref({
        usdt_fee: '996',
        usdt_address: '0x742d35Cc6634C0532925a3b844Bc9e',

    });
    let qrCodeImg = ref('')
    // 支付倒计时
    const timer = ref < NodeJS.Timeout | null > (null);
    let goodsTime = ref(1 * 60 * 60 * 1000)

    // 支付状态
    const paymentSuccess = ref(false);

    // 格式化金额
    const formattedAmount = computed(() => {
        return `${usdtInfo.value.usdt_fee}`;
    });
    // 生成二维码
    const generateQRCode = async () => {
        try {
            qrCodeImg.value = await QRCode.toDataURL(usdtInfo.value.usdt_address, {
                width: 180,
                margin: 1,
                color: {
                    dark: '#000000', // 二维码点颜色
                    light: '#ffffff' // 背景颜色
                },
                type: 'image/png',
                errorCorrectionLevel: 'H' // 高容错率
            });
        } catch (err) {
            console.error('生成二维码失败:', err);
        }
    };
    // 获取USDT支付数据
    let payUsdt = async () => {
        let res = await API_ORDER.payUsdt({
            order_sn: order_sn.value,
            platform: 'H5'
        })
        if (res.code == 1) {
            usdtInfo.value = res.data
            generateQRCode()
        }
    }
    // 选择支付方式
    const selectPaymentMethod = (methodId: string) => {
        if (methodId === 'usdt') {
            payUsdt()
        }
        selectedMethod.value = methodId;
        paymentMethods.value.forEach(method => {
            method.selected = method.id === methodId;
        });
        appStore.setPayment(methodId)

    };

    // 复制USDT地址
    const copyUsdtAddress = () => {
        navigator.clipboard.writeText(usdtInfo.value.usdt_address)
            .then(() => {
                showToast(t('home.OperationSuccessful'));
            })
            .catch(err => {
                console.error('复制失败:', err);
                showToast('复制失败，请手动复制');
            });
    };

    // 处理支付
    const handlePayment = () => {
        if (selectedMethod.value === 'paypal') {
            processPaypalPayment();
        } else if (selectedMethod.value === 'yue') {
            mouneyPay()
        } else {
            processUsdtPayment();
        }
    };

    let mouneyPay = async () => {
        let res = await API_ORDER.payMoney({
            order_sn: order_sn.value,
            platform: 'H5'
        })
        if (res.code == 1) {
            showLoadingToast({
                message: 'loading...',
                duration: 0,
                forbidClick: true
            });

            // 模拟支付处理
            setTimeout(() => {
                closeToast();
                showPaymentSuccess();
            }, 2000);
        }
    }

    // 处理PayPal支付
    const processPaypalPayment = () => {
        showLoadingToast({
            message: 'loading...',
            duration: 0,
            forbidClick: true
        });

        // 模拟支付处理
        setTimeout(() => {
            closeToast();
            showPaymentSuccess();
        }, 2500);
    };

    // 处理USDT支付
    const processUsdtPayment = () => {
        showConfirmDialog({
            title: t('home.ConfirmPayment'),
            message: t('home.PleasecompletedtransferUSDT'),
            confirmButtonText: t('home.confirm'),
            cancelButtonText: t('home.cancel')
        }).then(() => {
            showLoadingToast({
                message: 'loading...',
                duration: 0,
                forbidClick: true
            });

            // 模拟验证过程
            setTimeout(() => {
                closeToast();
                showPaymentSuccess();
            }, 3000);
        }).catch(() => {
            // 用户取消
        });
    };

    // 显示支付成功
    const showPaymentSuccess = () => {
        paymentSuccess.value = true;
        if (timer.value) {
            clearInterval(timer.value);
            timer.value = null;
        }
    };

    // 返回首页
    const goToHome = () => {
        router.push('/');
    };
    // 格式化倒计时显示
    const formattedTime = () => {
        // 到期时间
        let endTime = orderInfo.value.ext.expired_time * 1000
        // 获取当前时间
        let now = Math.floor(Date.now());
        // 剩余时间
        let remainingSeconds = Math.max(endTime - now, 0);
        goodsTime.value = remainingSeconds

    };
    let getOrderDetail = async () => {
        let res = await API_ORDER.orderDetail({
            id: order_sn.value
        })
        if (res.code == 1) {
            orderInfo.value = res.data
            formattedTime()
        }

    }
    // 页面加载时初始化
    onMounted(() => {
        appStore.setPayment('paypal')
        if (route.query) {
            order_sn.value = route.query.id
        }
        // 模拟从API获取订单信息
        setTimeout(() => {
            getOrderDetail()

        }, 500);
    });
</script>

<template>
    <div class="pay-container">
        <!-- 支付头部 -->
        <div class="pay-header">
            <div class="back-btn" @click="router.go('-1')">
                <van-icon name="arrow-left" />
                <span></span>
            </div>
            <div class="title">{{t('home.checkoutCounter')}}</div>
        </div>

        <!-- 支付成功页面 -->
        <div v-if="paymentSuccess" class="success-view">
            <div class="success-icon">
                <van-icon name="checked" size="80" color="#07c160" />
            </div>
            <div class="success-title">{{t('home.PaymentSuccessful')}}！</div>
            <div class="success-message">{{t('home.Thankyoupurchase')}}</div>
            <van-button type="primary" size="large" round class="home-btn" @click="goToHome">
                {{t('home.ReturntoHome')}}
            </van-button>
        </div>

        <!-- 支付内容页面 -->
        <div v-else class="pay-content">
            <!-- 订单摘要 -->
            <div class="order-summary">
                <div class="section-title">{{t('home.OrderInformation')}}</div>
                <div class="order-info">
                    <div class="info-row">
                        <span class="label">{{t('home.Ordernumber')}}</span>
                        <span class="value">{{ orderInfo.order_sn }}</span>
                    </div>
                    <!-- <div class="info-row">
                        <span class="label">商品描述</span>
                        <span class="value">{{ orderInfo.description }}</span>
                    </div> -->
                    <div class="info-row">
                        <span class="label">{{t('home.Creationtime')}}</span>
                        <span class="value">{{ orderInfo.createtime }}</span>
                    </div>
                </div>
                <div class="total-row">
                    <span class="label">{{t('home.Amountpayable')}}</span>
                    <span class="value">{{ orderInfo.order_amount }}</span>
                </div>
            </div>

            <!-- 支付方式 -->
            <div class="payment-methods">
                <div class="section-title">{{t('home.Selectpaymentmethod')}}</div>
                <div v-for="method in paymentMethods" :key="method.id" class="payment-method"
                    :class="{ selected: method.selected }" @click="selectPaymentMethod(method.id)">
                    <div class="method-icon" :style="{ backgroundColor: method.color }">
                        <i v-if="method.icon === 'paypal'" class="fab fa-paypal">
                            <img src="@/assets/shop/paypal.png" alt="">
                        </i>
                        <i v-else-if="method.icon === 'usdt'" class="fas fa-coins">
                            <img src="@/assets/shop/USDT.png" alt="">
                        </i>
                        <i v-else class="fas fa-coins">
                            <img src="@/assets/shop/yue.png" alt="">
                        </i>
                    </div>
                    <div class="method-info">
                        <div class="method-name">{{ method.name }}</div>
                        <div class="method-desc">{{ method.description }}</div>
                    </div>
                    <div class="method-radio">
                        <van-radio :name="method.id" v-model="selectedMethod" />
                    </div>
                </div>
            </div>

            <!-- USDT支付详情 -->
            <div v-if="selectedMethod === 'usdt'" class="usdt-details">
                <div class="section-title">USDT{{t('home.PaymentInstructions')}}</div>
                <div class="payment-instructions">
                    <p>{{t('home.Pleasetransfer')}} <strong>{{ formattedAmount }}</strong> USDT
                        {{t('home.Tofollowingaddress')}}：</p>
                    <!-- <p>转账完成后请点击"确认支付"按钮</p> -->
                </div>
                <div class="qr-container">
                    <div class="qr-code">
                        <img :src="qrCodeImg" alt="USDT QR Code" />
                    </div>
                    <!-- <p>扫描二维码支付</p> -->
                </div>
                <div class="address-container">
                    <div class="address-label">USDT{{t('home.WalletAddress')}}</div>
                    <div class="address-value">
                        <span>{{ usdtInfo.usdt_address }}</span>
                        <van-button size="small" class="copy-btn" @click="copyUsdtAddress">
                            <van-icon name="copy" />
                            {{t('home.copy')}}
                        </van-button>
                    </div>
                </div>

            </div>
            <div class="timer">
                <van-icon name="clock" />
                {{t('home.Remainingpaymenttime')}}: <van-count-down :time="goodsTime" />
            </div>
            <!-- 支付按钮 -->
            <div class="pay-actions">
                <van-button round block type="primary" size="large" class="pay-button" @click="handlePayment">
                    {{t('home.ConfirmPayment')}}
                </van-button>
            </div>
        </div>


    </div>
</template>

<style lang="less" scoped>
    @import url('./index.less');
</style>